from django.contrib import admin
from django import forms
from django.utils.translation import ugettext_lazy as _
from gironimo.page.models import Page


class PageAdminForm(forms.ModelForm):
    url = forms.RegexField(label=_('URL'), max_length=100, regex=r'^[-\w/_\.]+$',
        help_text=_("Beispiel: '/about/contact'. Sicherstellen das ein vorangegangenes Slash angegeben ist."),
        error_message=_('Nur Zahlen, Buchstaben, Querstriche, Unterstriche und Slashes erlaubt.'))
    
    def clean_base_template(self):
        from django.template.loader import find_template_source
        from django.template import TemplateDoesNotExist
        value = self.cleaned_data.get('base_template')
        if value:
            try:
                find_template_source(value)
            except TemplateDoesNotExist:
                raise forms.ValidationError(_(u'Template existiert nicht.'))
        return value
    
    class Meta:
        model = Page


class PageAdmin(admin.ModelAdmin):
    form = PageAdminForm
    fieldsets = [
        (None,                    {'fields': ['title', 'url', 'base_template', 'content',]}),
        (_('HTML'),               {'fields': ['html_title', 'html_description', 'html_keywords',], 'classes': ['collapse']}),
    ]
    list_display = ('title', 'created', 'url', 'base_template')
    search_fields = ['title',]
    date_hierarchy = 'created'
    list_filter = ['created', 'base_template',]


admin.site.register(Page, PageAdmin)

